import shutil, os
from pathlib import Path
import datetime
import  MyUtils

def copyModelFile(currentPath, dst_folders, files=[]):
    '''
    currentPath = "xxx/"
    dst_folders = "xxx/"
    '''
    for file in files:
        source_file = currentPath+file
        toPath = dst_folders+file
        fileFmt = os.path.splitext(source_file)[-1]
        if source_file == toPath:
             continue
        res = MyUtils.copyFile(source_file, toPath, [fileFmt])

        #多参文件更新
        fileNameAll = os.path.split(source_file)[-1]
        mulParamsDirPath = currentPath+os.path.splitext(fileNameAll)[0]
        toMulParamsDirPath = dst_folders+os.path.splitext(fileNameAll)[0]
        if os.path.exists(mulParamsDirPath):
            MyUtils.copyDir(mulParamsDirPath, toMulParamsDirPath)


def updateCommonStepParams2222(srcPath, dstPath, stepIdxList=[]):
    '''
    更新通用step参数，stepIdxList通用参数列表
    srcPath = xx/paramster//
    dstPath = xx/paramster//
    '''
    files, wholeFiles = MyUtils.recursive_listdir(srcPath)
    for stepIdx in stepIdxList:
        for file in files:
            idx = file.find(str(stepIdx)+"_")
            if idx == 0:
                print("from ",srcPath+file+"\ncopy to dst parmaster file: ", dstPath+file)
                copyModelFile(srcPath, dstPath, [file])
                break

def updateCommonStepParams(srcPath, dstPath,stepIdxList=[],stepIdxListNot=[]):
    '''
    注意：stepIdxListNot, stepIdxList不能同时使用, stepIdxListNot为空时，全部更新
    stepIdxListNot 不更新，其余全更新，
    stepIdxList 更新，其余不更新，
    srcPath = xx/paramster/
    dstPath = xx/paramster/
    '''
    if len(stepIdxListNot)>0 and len(stepIdxList)>0:
        print("stepIdxListNot, stepIdxList不能同时使用")
        exit(0)
    files, wholeFiles = MyUtils.recursive_listFiles(srcPath)
    if len(stepIdxList)>0:
        #仅更新列表step
        for stepIdx in stepIdxList:
            for file in files:
                idx = file.find(str(stepIdx)+"_")
                if idx == 0:
                    print("\ncopy to dst parmaster file: ", dstPath+file)
                    copyModelFile(srcPath, dstPath, [file])
                    break
    elif(len(stepIdxListNot)>=0):
        #忽略列表step
        for file in files:
            isIgnore = False
            for stepIdx in stepIdxListNot:
                idx = file.find(str(stepIdx)+"_")
                if idx == 0:
                    isIgnore = True
                    break
            if isIgnore:
                continue
            print("from ",srcPath+file+"\ncopy to dst parmaster file: ", dstPath+file)
            copyModelFile(srcPath, dstPath, [file])

            #是否有多参文件夹
            # 提取父路径
            #parent_path_src = os.path.dirname(srcPath)

            # 提取文件名（包含扩展名）
            #file_name_with_ext = os.path.basename(srcPath)

            # 提取文件名（不包含扩展名）
            file_name = os.path.splitext(file)[0]
            if os.path.exists(srcPath+file_name):
                MyUtils.copyDir(srcPath+file_name,dstPath+file_name)


            



def updateStepAddDel(srcParametersPath, dstParametersPath):
    '''
    更新新增删除的step, 
    dstParametersPath = dstModelPath+ '/Parameters/'
    '''
    files, wholeFiles = MyUtils.recursive_listdir(srcParametersPath)
    for file in files:
        dstFile = dstParametersPath+file
        if( not os.path.exists(dstFile) or file.find("SubmitDefectsStep")>0):
                paramsterFile = [file]
                print("add new step params, start copy...")
                print(">>>  from ",srcParametersPath,"\n copy to dst parmaster file: ", dstFile)
                copyModelFile(srcParametersPath, dstParametersPath, paramsterFile)
    return

def updateModelLog(modelPath, logInfo):
    '''
    modelPath = "xxx/"
    '''
    if( not os.path.exists(modelPath)):
        print("path not exist: ", modelPath)
        exit(0) 
    currentTime = datetime.datetime.now().strftime('%Y-%m-%d  %H:%M:%S')
    toPath = modelPath+"z-record.me"
    print("调试记录的路径: ", toPath)
    with open(toPath,"a+",  encoding='utf-8') as f:
        f.write(currentTime)
        f.write("->\n")
        f.write(logInfo)
        f.write("\n")

def modelUpdateDemo(commitInfo,srcModelPath="model-xx/",dstModelPathList=["model-xx/"],stepIdxListNot=[],publishPath=None):
    '''
    publishPath="xx/"
    '''
    currentTime = datetime.datetime.now().strftime('%Y-%m-%d  %H:%M:%S')
    currentDate = datetime.datetime.now().strftime('%Y-%m-%d')
    
    if( not os.path.exists(srcModelPath)):
            print("srcModelPath path not exist: ", srcModelPath)
            exit(0)
    else:
         print(">>> src model: ", srcModelPath)
         print(">>>")
    
    vec = srcModelPath.split('/')
    if len(vec) < 2:
        print("error: idx = srcModelPath.rfind('/')")
        exit(0)
    

    #记录发布内容
    if publishPath != None:
        publish = publishPath+'publish-'+commitInfo+'/'
        # if(os.path.exists(publish)):
        #     utils.deleteDir(publish)
        MyUtils.createDirs(publish)

        if(not os.path.exists(publish+commitInfo+".txt")):
            with open(publish+commitInfo+".txt", 'w', encoding='utf-8') as file:
                file.write(commitInfo)

    
    commit = commitInfo
    srcModelName = vec[len(vec)-2]
    updateModelLog(srcModelPath, srcModelName+":"+commit)

    srcParametersPath = srcModelPath+ '/Parameters/'
    for dstModelPath in dstModelPathList:
        print(dstModelPath)
        dstParametersPath = dstModelPath+ '/Parameters/'

        vec = dstModelPath.split('/')
        if len(vec) < 2:
            print("error: idx = srcModelPath.rfind('/')")
            exit(0)

        if vec[-1] == "":
            dstModelName = vec[len(vec)-2]
        else:
            dstModelName = vec[len(vec)-1]
        
        #目标model不存在，copy
        if( not os.path.exists(dstModelPath)):
            print("dstModelPath path not exist， copy to: ", dstModelPath)
            MyUtils.copyDir(srcModelPath, dstModelPath)
            MyUtils.createDirs(dstModelPath+"../orgImages_"+dstModelName)
        else:
            print(">>> dstModelPath model: ", dstModelPath)
            print(">>>")



        if( not os.path.exists(dstModelPath)):
            print("path not exist: ", dstModelName+":"+dstModelPath)
            exit(-1)

        if(srcModelPath != dstModelPath):
            updateModelLog(dstModelPath,dstModelName+": "+commit)
        
            #0，更新bin
            MyUtils.copyDir(srcModelPath+"/bin/", dstModelPath+"/bin/")

            #1，更新流程图
            copyModelFile(srcModelPath, dstModelPath, ['algDef.json','DftParamMapping.json', 'defectType.json', 'debugStepList.json'])

            #2，更新ROI定位model
            MyUtils.copyDir(srcModelPath+"/ROI/", dstModelPath+"/ROI/")

            updateCommonStepParams(srcParametersPath, dstParametersPath,stepIdxListNot= stepIdxListNot) 

            #4,更新新增step参数
            paramsNameList = []
            paramsNameList, wholeFiles = MyUtils.recursive_listFiles(srcParametersPath)
            for file in paramsNameList:
                dstFile = dstParametersPath+file
                if( not os.path.exists(dstFile)):
                    paramsterFile = [file]
                    print("add new step params, start copy...")
                    print(">>>  copy to dst parmaster file: ", dstFile)
                    copyModelFile(srcParametersPath, dstParametersPath, paramsterFile)


            #5,更新新增step多参数文件夹
            mulParamsDirs, wholeFiles = MyUtils.recursive_listDir(srcParametersPath)
            for dir in mulParamsDirs:
                dstDir = dstParametersPath+dir
                if( not os.path.exists(dstDir)):
                    MyUtils.copyDir(srcParametersPath+dir, dstDir)
                    print("add new step params, start copy...")
                    print(">>>  copy to dst parmaster dir: ", dstDir)

 
        #删除多参文件夹
        paramsFileDir,paramsFileDirAllPath = MyUtils.recursive_listDir(dstParametersPath)
        paramsNameList, wholeFiles = MyUtils.recursive_listFiles(dstParametersPath)
        for i in range(len(paramsFileDir)):
            fileDir = paramsFileDir[i]
            isMulParamsDir = False
            for paramsFile in paramsNameList:
                name,extension = os.path.splitext(paramsFile)
                if name == fileDir:
                    isMulParamsDir = True
                    break
            if not isMulParamsDir:
                MyUtils.deleteDir(paramsFileDirAllPath[i])

        if publishPath != None:
            #发布model
            print("\n\n>>>publish: ", dstModelName)
            MyUtils.deleteDir(publish+dstModelName)
            MyUtils.copyDir(dstModelPath,publish+dstModelName)
        continue

    
          
    return


class  UpdateModel:
    def __init__(self, rootPath,dstProductsList,prefix,publishPath=None,stepIdxListNot=[]):
        '''
        rootPath = 'E:\\workspace\\0_model\\夏普\\夏普模组\\edge-4k/'

        dstProductsList=[
            "CG-12.0矩形2","CG-12.0矩形有壳2"
            ,"CG-12.2矩形2","CG-12.2矩形有壳2"
            ]
    
        prefix = "model-"  #model名称的前缀
        publish = rootPath
        stepIdxListNot = []
        '''
        self.rootPath = rootPath
        self.dstProductsList = dstProductsList
        self.prefix = prefix
        self.publish=publishPath
        self.stepIdxListNot=stepIdxListNot
        pass

    def update(self,srcProduct, commitInfo):
        '''
        srcProduct="CG-12.2异形有壳3"
        commitInfo = "型号CG-12.2异形有壳3建模，缝隙测量独立区域裁图"
        '''
    
        print("commitInfo: ", commitInfo)
        print("发布model：", self.publish)
        inputStr = input("当前源model："+srcProduct+"\n是否确认更新(y/n): ")
        print(inputStr)
        if inputStr != 'y':
            print("指令错误: " + inputStr)
            exit(0)

        commitInfo = commitInfo+", 同步model-"+srcProduct

        dstModelPathList = []
        for dstProducts in self.dstProductsList:
            dstModelPathList.append(self.rootPath+dstProducts+"/"+self.prefix+dstProducts+"/")
        
        srcProductPath=self.rootPath+srcProduct+"/"+self.prefix+srcProduct+"/"

        
        modelName = srcProductPath.split('/')[-1]
        srcModelPath = srcProductPath
        if( not os.path.exists(srcModelPath)):
                print("srcModelPath path not exist: ", srcModelPath)
                exit(0)
        else:
            print(">>> src model: ", srcModelPath)
            print(">>>")
        modelUpdateDemo(commitInfo, srcModelPath,dstModelPathList,self.stepIdxListNot,self.publish)
        return


def test():
    return
    currentTime = datetime.datetime.now().strftime('%Y-%m-%d  %H:%M:%S')
    currentDate = datetime.datetime.now().strftime('%Y-%m-%d')

    commitInfo = "完善焊盘debug输出"
    idx_0 = 31.5
    dstModelIdx = [12.3, 15.6, 27.2,27.3, 27, 34, 49, 65, 85]
    modelPath = 'F:/workespace/woge-images/'+str(idx_0)+'_inch/'
    modelName = "model-"+str(idx_0)+"inch-"
    srcModelPath = modelPath+modelName
    if( not os.path.exists(srcModelPath)):
            print("path not exist: ", srcModelPath)
            exit(0)
    else:
         print(">>> src model: ", srcModelPath)
         print(">>>")

    srcParametersPath = srcModelPath+ '/Parameters/'
    for idx in dstModelIdx:
        modelPath = 'F:/workespace/woge-images/'+str(idx)+'_inch/'
        modelName = "model-"+str(idx)+"inch-"
        dstModelPath = modelPath+modelName

        if( not os.path.exists(dstModelPath)):
            print("path not exist: ", dstModelPath)
            exit(0)
        else:
            print(">>> dstModelPath model: ", dstModelPath)
            print(">>>")

        print(dstModelPath)
        commit = modelName+commitInfo+currentDate
        updateModelLog(dstModelPath, commit)

        #0，更新bin
        MyUtils.copyDir(srcModelPath+"/bin", dstModelPath+"/bin")

        #1，更新流程图
        copyModelFile(srcModelPath, dstModelPath, ['algDef.json'])

        #2，更新缺陷类型
        source_file = srcModelPath+ '/defectType'
        toPath = dstModelPath + "/defectType"
        MyUtils.createDirs(toPath)
        copyModelFile(source_file, toPath, ['defectType.json'])

        #3,更新新增step参数
        dstParametersPath = dstModelPath+ '/Parameters/'
        updateStepAddDel(srcParametersPath, dstParametersPath=dstParametersPath)

        #4,更新通用step参数，大焊盘
        updateCommonStepParams(srcParametersPath, dstParametersPath,[72,73,74,75,87,117])
        #4,更新通用step参数，焊盘
        updateCommonStepParams(srcParametersPath, dstParametersPath,[199,76,200, 
                                                                     201,125,202,
                                                                     203,14,131,
                                                                     158,159,160,
                                                                     140,141,142,
                                                                     147,148,149,150])
        #4,更新通用step参数，油墨
        updateCommonStepParams(srcParametersPath, dstParametersPath,[])
        #4,更新通用step参数，jinshouzhi
        updateCommonStepParams(srcParametersPath, dstParametersPath,[163,184,185,197,23,129,193,187,191])

if __name__ == "__main__":  
    print("\ndemo:")
    #test()

